
var webSocket  = null;
var connected  = false;
var checkboard = null;
var cbSize = 15;
var myCamp = "none";

$(document).ready(function() {
	/*
	$("#blackReady").addClass("hid");
	$("#whiteReady").addClass("hid");
	$("#blackReady").removeClass("readyP");
	$("#whiteReady").removeClass("readyP");
	createRoomSuccess();
	
	checkboard = new Checkerboard("checkboard", 15, "black", null);
	$("#divMain").append(checkboard.getEmpty());
	*/
	/////////////////////////////////////////////////////
	
	
	initWebsocket();

	var txtRoomTitle = $("#txtRoomTitle");
	var txtCBSize = $("#txtCBSize");

	txtRoomTitle.focus(function() {
		$("#txtRoomTitle").removeClass("invalid");
	});
	
	txtCBSize.focus(function() {
		$("#txtCBSize").removeClass("invalid");
	});
	
	$("#btnRoomOk")[0].onclick = function() {
		if(txtRoomTitle.val() == null || txtRoomTitle.val() == "") {
			txtRoomTitle.addClass("invalid");
			return;
		}
		
		var size = txtCBSize.val();
		if(size > 2 && size < 31) cbSize = size;
			else {
				txtCBSize.addClass("invalid");
				return;
			}
		registRoomConfig();
	};

	$("#txtRoomTitle").bind('keydown',function(event) {
		if(event.keyCode == "13") {
			$("#btnRoomOk")[0].click();
		}
   });

	$("#txtRoomPassword").bind('keydown',function(event) {
		if(event.keyCode == "13") {
			$("#btnRoomOk")[0].click();
		}
   });

	$("#txtRoomTitle").focus();

	////////////////////////////////

	$("#blackReady").click(function() {
		ready("black");
	});
	
	$("#whiteReady").click(function() {
		ready("white");
	});
	
});

function ready(camp) {
	if(!connected || webSocket == null) return;
	webSocket.send(JSON.stringify({
		type:"playerReady",
		cmp:camp
	}));
}

function selectBlack() {
	myCamp = "black";
}

function selectWhite() {
	myCamp = "white";
}

function beVisitor() {
	myCamp = "none";
}

//隐藏准备按钮
function hideReadyButton() {
	$("#blackReady").addClass("hid");
	$("#whiteReady").addClass("hid");
	$("#blackReady").removeClass("readyP");
	$("#whiteReady").removeClass("readyP");
}

var hasNotControlPanel = true;
function gameStart(newCheckerboard, cmp) {
	
	//添加棋盘
	checkboard = newCheckerboard;
	$("#divMain").append(checkboard.getEmpty());

	//隐藏准备按钮
	hideReadyButton();

	if(cmp != null && cmp != "" && cmp != "none") {
		//设定撤回按钮
		let btnRbk = $("#btnRollback");
		btnRbk.removeClass("hid");
		btnRbk.removeClass("cfm");
		btnRbk.addClass("rbk");
		btnRbk[0].onclick = function() {
			if(checkboard != null) {
				if(checkboard.getUserConfirmed()) {
					checkboard.requestRollback();
				} else {
					if($("#btnRollback").text() == "确认战果") {
						gameEnd();
					} else {
						runEnd();
					}
					$("#btnRollback").text("撤回棋子");
					$("#btnRollback").addClass("hid");
				}
			}
		};
		
		var divSett = $("#divSetting");
		hasNotControlPanel = divSett.hasClass("hid");
		//alert(hasNotControlPanel);
		$("#btnRoomOk").addClass("hid");
		$("#divSetting").addClass("hid");
	}
}

function confirmed() {
	if(!hasNotControlPanel) {
		$("#btnRoomOk").removeClass("hid");
		$("#divSetting").removeClass("hid");
		hasNotControlPanel = true;
	}
	
	$("#lblcfm").addClass("hid");
	//显示准备按钮
	$("#blackReadyInner").css("background-image", "none");
	$("#whiteReadyInner").css("background-image", "none");
	$("#blackReady").removeClass("hid");
	$("#whiteReady").removeClass("hid");
	$("#blackReady").addClass("readyP");
	$("#whiteReady").addClass("readyP");
}

//移除棋盘
function removeCheckerboard() {
	if(checkboard != null) {
		$("#checkerboard_checkboard").remove();
		checkboard.setUserConfirmed(true);
		checkboard = null;
	}
}

function gameEnd() {
	removeCheckerboard();
	$("#lblcfm").removeClass("hid");
}

function runEnd() {
	//移除棋盘
	removeCheckerboard();
	confirmed();
}

function initWebsocket() {
	connected = false;
	
	webSocket = new WebSocket(
		"ws://" + 
		location.hostname + ":" + 
		location.port + "/" + 
		projectRootDir(location.pathname) + 
		"/battleRoom"
	);

	webSocket.onopen = function() {
		connected = true;
	}

	webSocket.onclose = function() {
		connected = false;
	}
	
	webSocket.onmessage = function(data) {
		console.log("dispatching...");
		var response = JSON.parse(data.data);
		console.log(response.type);
		switch(response.type) {
			case "getWSSessionId":
				//向后端PlayerServlet发请求，注册Websocket Session ID, 并创建Player
				registPlayer(response.WSID);
				break;
			case "swap_host": {//新房主上任
				let confmed = false;
				if(response.runOfBattle == true) {
					checkboard.setUserConfirmed(false);
					let btnRbk = $("#btnRollback");
					btnRbk.removeClass("rbk");
					btnRbk.addClass("cfm");
					btnRbk.text("对方逃跑，返回房间");
					confmed = true;
				}
				if(response.confirmed == true) {
					confirmed();
					confmed = true;
				}
				if(!confmed) getReady(response);
				
				$("#btnRoomOk").removeClass("hid");
				$("#divSetting").removeClass("hid");
				createRoomSuccess();
				break;
			}
			case "configRoomSucceed":
				updateRoomConfig(response);
				createRoomSuccess();
				break;
			case "challenger_leave":
			case "host_leave":
				if(myCamp == "none") runEnd();
			case "getReady": {
				let confmed = false;
				if(response.runOfBattle == true) {
					console.log(myCamp);
					if(checkboard != null) checkboard.setUserConfirmed(false);
					let btnRbk = $("#btnRollback");
					btnRbk.removeClass("rbk");
					btnRbk.addClass("cfm");
					btnRbk.text("对方逃跑，返回房间");
					confmed = true;
				}
				if(response.confirmed == true) {
					confirmed();
					confmed = true;
				}
				if(!confmed) getReady(response);
				break;
			}
			case "go":
				checkboard.go(response.row, response.col, response.cmp);
				break;
			case "rollback":
				checkboard.rollback(response.rbk[0], response.rbk[1], response.rbk[2], response.rbk[3]);
				break;
			case "configCheckerboard":
				
				if(checkboard == null) {
					if(response.cmp == "black") {
						selectBlack();
					} else if(response.cmp == "white") {
						selectWhite();
					} else {
						beVisitor();
					}
					gameStart(new Checkerboard("checkboard", response.siz, response.cmp, webSocket), response.cmp);
				}
				
				break;
			case "getCheckerboard": {
				
				if(checkboard == null) {
					gameStart(new Checkerboard("checkboard", response.siz, "none", webSocket), "none");
				}
				//console.log("response.data: " + response.data);
				for(ijc of response.data) {
					checkboard.go(ijc[0], ijc[1], value2Camp(ijc[2]));
					console.log("history> i: " + ijc[0] + ", j: " + ijc[1] + ", camp: " + value2Camp(ijc[2]));
				}
				break;
			}
			case "clean": 
				if(checkboard != null) checkboard.clean();
				break;
			case "blackWin": {
				checkboard.go(response.row, response.col, response.cmp);
				checkboard.showWinBy(response.win);
				//设定撤回按钮
				checkboard.setUserConfirmed(false);
				let btnRbk = $("#btnRollback");
					btnRbk.removeClass("rbk");
					btnRbk.addClass("cfm");
					btnRbk.text("确认战果");
				break;
			} case "whiteWin": {
				checkboard.go(response.row, response.col, response.cmp);
				checkboard.showWinBy(response.win);
				//设定撤回按钮
				checkboard.setUserConfirmed(false);
				let btnRbk = $("#btnRollback");
					btnRbk.removeClass("rbk");
					btnRbk.addClass("cfm");
					btnRbk.text("确认战果");
				break;
			} case "draw": {
				//alert("Draw !");
				//设定撤回按钮
				checkboard.setUserConfirmed(false);
				let btnRbk = $("#btnRollback");
					btnRbk.removeClass("rbk");
					btnRbk.addClass("cfm");
					btnRbk.text("确认战果");
				break;
			} case "playerConfirm": {
				removeCheckerboard();
				confirmed();
				break;
			}
		}
	};
}

function getReady(data) {
	let blackimg = data.blackImg;
	let whiteimg = data.whiteImg;
	
	if(blackimg != null) {
		if(blackimg == "none") {
			$("#blackReadyInner").css("background-image", "none");
		} else {
			$("#blackReadyInner").css("background-image", headPicPathname(blackimg));
		}
	}
	if(whiteimg != null) {
		if(whiteimg == "none") {
			$("#whiteReadyInner").css("background-image", "none");
		} else {
			$("#whiteReadyInner").css("background-image", headPicPathname(whiteimg));
		}
	}
}

function createRoomSuccess() {
	let divRoomS = $("#divRoomSettings");
	divRoomS.removeClass("top50");
	divRoomS.addClass("top120");
	$("#btnRoomCancel").removeClass("hid");
}

function updateRoomConfig(data) {
	$("#txtRoomTitle").val(data.roomTitle);
	document.getElementById("chkWatchable").checked = data.roomWatch;
	$("#txtCBSize").val(data.cbSize);
}

function enterRoomSuccess(data) {
	updateRoomConfig(data);
	getReady(data);
	$("#btnRoomOk").addClass("hid");
	$("#divSetting").addClass("hid");
}

function registPlayer(wsid) {
	$.ajax({
		url:"regist.player",
		type:"post",
		data:{
			wsSessionId:wsid
		},
		dataType:"json",
		success:function(data) {
			switch(data.type) {
				case "enterRoom":
					enterRoomSuccess(data);
					break;
				case "creatRoom":
					break;
			}
		}
	});
}

function registRoomConfig() {

	$("#txtRoomTitle").blur();
	$("#txtRoomPassword").blur();

	if(!connected || webSocket == null) return;
	
	var title = $("#txtRoomTitle").val();
	if(title == null || title == "") return;

	var pass = $("#txtRoomPassword").val();
	if(pass == null || pass == "") pass = null;
	
	var watch = document.getElementById("chkWatchable").checked;

	var size = $("#txtCBSize").val();
	
	var msg = JSON.stringify({
		type:"configRoom",
		roomTitle:title,
		roomPass:(pass == null? null: sha256.hex(pass)),
		roomWatch:watch,
		cbSize:size
	});

	webSocket.send(msg);
}